import { _decorator, Component, Layers, log, Node, resources, Sprite, SpriteFrame, UITransform } from 'cc';
import { TileManager } from './TileManager';
import { createUINode, randomByRange } from '../../Utils';
import DataManager from '../../Runtime/DataManager';
import ResourceManager from '../../Runtime/ResourceManager';
const { ccclass, property } = _decorator;

export const TILE_WIDTH = 55;
export const TILE_HEIGHT = 55;

@ccclass('TileMapManager')
export class TileMapManager extends Component {
    async init() {
        try {
            const spriteFrames = await ResourceManager.Instance.loadDir("texture/tile/tile");
            const { mapInfo } = DataManager.Instance;
            DataManager.Instance.tileInfo = [];
            // 双层遍历
            for (let i = 0; i < mapInfo.length; i++) {
                const column = mapInfo[i];
                DataManager.Instance.tileInfo[i] = [];
                for (let j = 0; j < column.length; j++) {
                    const item = column[j];
                    if (item.src === null || item.src === null) {
                        continue;
                    }


                    let number = item.src;
                    if( (number === 1 || number === 5 || number === 9) && i%2 ===0 && j%2 === 0  ) {
                        number += randomByRange(0,4)
                    }
                    const imgSrc = `tile (${number})`;



                    const node = createUINode(); // 这一步完全可以使用预制体来做
                    const spriteFrame = spriteFrames.find(v => v.name === imgSrc) || spriteFrames[0];
                    const tileManager = node.addComponent(TileManager); // 添加上脚本
                    const type = item.type;
                    tileManager.init(type, spriteFrame, i, j);
                    DataManager.Instance.tileInfo[i][j] = tileManager;
                    node.setParent(this.node);
                }
            }
            console.log('地图初始化完成');
        } catch (error) {
            console.log('创建节点失败', error);
        }
    }


}


